package com.osce.common.utils;

import com.doudou.core.container.ListUtil;
import com.doudou.core.container.SetUtil;
import com.doudou.core.throwable.GlobalException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;

public class ValidatorUtils {

    private static Validator validatorFast = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
    private static Validator validatorAll = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();

    /**
     * 校验遇到第一个不合法的字段直接返回不合法字段，后续字段不再校验
     */
    public static <T> void validate(T domain) {
        Set<ConstraintViolation<T>> validateResult = validatorFast.validate(domain);
        if(ListUtil.isNotEmpty(validateResult)) {
            throw new GlobalException(SetUtil.getFirst(validateResult).getMessage());
        }
    }
    
    /**
     * 校验所有字段并返回不合法字段
     */
    public static <T> void validateAll(T domain) {
        Set<ConstraintViolation<T>> validateResult = validatorAll.validate(domain);
        if(ListUtil.isNotEmpty(validateResult)) {
            String msgs = validateResult.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("\n"));
            throw new GlobalException(msgs.toString());
        }
    }
    
}
